/*
 * ViewStory.java
 * Activity view single story with comments
 */
package edu.ntu.mobilestomp;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import edu.ntu.helper.CommentList;
import edu.ntu.helper.CommentXMLHandler;
import edu.ntu.helper.RestClient;
import edu.ntu.helper.RestClient.RequestMethod;
import edu.ntu.helper.StoryList;
import edu.ntu.helper.StoryXMLHandler;

public class ViewStory extends TabActivity {
	private int mStoryID;
    private ImageView iv;
    private Bitmap bm;
    private EditText etTitle;
    private TextView etDetails;
    private EditText etTag1;
    private EditText etTag2;
    private EditText etTag3;
    private EditText etNewComment;

    private Button addCommentButton;
    private ProgressDialog dialog;
    private ListView mainListView ;  
    private CommentListAdapter listAdapter ;
    
    private int storyIndex;
    private String storyTitle;    
    private String storyDesc;
    private String storyLink;
    private String storyTags;
    private ArrayList<String> allCommText = null;
    private ArrayList<String> allTimestamp = null;
    
	private BitmapFactory.Options options = new BitmapFactory.Options();

    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TabHost tabHost = getTabHost();
        LayoutInflater.from(this).inflate(R.layout.viewstory, tabHost.getTabContentView(), true);

        Bundle extras = getIntent().getExtras(); 
        if(extras !=null)
        {
        	mStoryID = extras.getInt("storyID");
        }
        // Creating tab menu
        tabHost.addTab(tabHost.newTabSpec("picTab")
                .setIndicator("Picture")
                .setContent(R.id.picture));
        tabHost.addTab(tabHost.newTabSpec("storyTab")
                .setIndicator("Story")
                .setContent(R.id.storyView));
        tabHost.addTab(tabHost.newTabSpec("commentsTab")
                .setIndicator("Comments")
                .setContent(R.id.commentsView));
        tabHost.addTab(tabHost.newTabSpec("tagsTab")
                .setIndicator("Tags")
                .setContent(R.id.tagsView));

		// Show Processing dialog
        showDialog(1);

        // AsyncTask to download story details and picture
		new DownloadStoryTask().execute(mStoryID);
		
    }
	// AsyncTask to download comments and picture
	private class DownloadStoryTask extends AsyncTask<Integer, Integer, String> {

		HttpURLConnection conn = null;

		@Override
		protected String doInBackground(Integer... IDs) {
			
			StoryList storyListT = null;
			CommentList commentListT = null;

			// getting story information
			storyListT = doGetStory(IDs[0]);

		    storyIndex = storyListT.getIndex().get(0);
		    storyTitle = storyListT.getTitle().get(0);
		    storyDesc = storyListT.getDetails().get(0);
		    Log.v("stodesc", storyDesc);
		    
		    try {
				storyDesc = URLDecoder.decode(storyDesc, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    storyLink = storyListT.getLink().get(0);
		    storyTags = storyListT.getTags().get(0);
		    
		    // getting comments of story
		    commentListT = doGetComments(IDs[0]);
		    if(commentListT != null){
		    	allCommText = commentListT.getComment();
		    	allTimestamp = commentListT.getSubmit_time();
		    }
			return null;
		}
		
		
	    protected void onPostExecute(String result) {

			Bitmap bitmap;
			try {
				
		        options.inSampleSize = 4;
				bitmap = BitmapFactory.decodeStream((InputStream) new URL(getString(R.string.base_url)+ "/uploads/" + storyLink).getContent(), null, options);
		        iv = (ImageView) findViewById(R.id.picture);

		        iv.setImageBitmap(bitmap);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			etTitle = (EditText) findViewById(R.id.title);
	        etDetails = (TextView) findViewById(R.id.story);
	        etTag1 = (EditText) findViewById(R.id.tag1);
	        etTag2 = (EditText) findViewById(R.id.tag2);
	        etTag3 = (EditText) findViewById(R.id.tag3);
	        etNewComment = (EditText) findViewById(R.id.CommentText);
	        addCommentButton = (Button) findViewById(R.id.addCommentButton);
	        
	        addCommentButton.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					doAddComment(etNewComment.getText().toString(), mStoryID);					
				}
			});
			etDetails.setText(storyTitle);
			etDetails.setText(storyDesc);
			
			Log.v("this is the storydesc", storyDesc);
			
			String[] items = storyTags.split(",");
			if(items.length>0) etTag1.setText(items[0]);
			if(items.length>1) etTag2.setText(items[1]);
			if(items.length>2) etTag3.setText(items[2]);
			
			// populating comments
            // Find the ListView resource.   
            mainListView = (ListView) findViewById( R.id.commentList);
            if(allCommText !=null){
            	listAdapter = new CommentListAdapter(getApplicationContext(), allCommText, allTimestamp);
            	
	            // Set the ArrayAdapter as the ListView's adapter.  
	            mainListView.setAdapter( listAdapter ); 
            }

			dialog.dismiss();
	    }
	    
		private void doAddComment(String aComment, int mID) {
			RestClient client = new RestClient(getString(R.string.base_url) + "/add_new_comment.php");
			
			client.AddParam("atext", aComment);
			client.AddParam("astory_index", mID+"");

			try {
			    client.Execute(RequestMethod.POST);
			} catch (Exception e) {
			    e.printStackTrace();
			}
			String response = client.getResponse();
			
			Toast.makeText(getApplicationContext(), response, 5).show();
	        showDialog(1);
	        
			new DownloadStoryTask().execute(mStoryID);
			etNewComment.setText("");
		}
		
	    public StoryList doGetStory(int storyID){

			StoryList storyListRecords = null;
			StoryXMLHandler.storyList = null;

			RestClient client = new RestClient(getString(R.string.base_url)+"/get_pic_by_ID.php");
			client.AddParam("ID", ""+storyID);

			try {
				client.Execute(RequestMethod.GET);
			} catch (Exception e) {
				e.printStackTrace();
			}

			String storyResponse = client.getResponse();
			String storyReplacement = null;
			try {

				/** Handling XML */
				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser sp = spf.newSAXParser();
				XMLReader xr = sp.getXMLReader();

				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
				StoryXMLHandler myXMLHandler = new StoryXMLHandler();
				xr.setContentHandler(myXMLHandler);
				storyReplacement = storyResponse.replace("\n", "");
				storyReplacement = storyReplacement.trim();

				Log.v("this is response", storyResponse);
				//Log.v("this is replacemment", replacement);

				InputSource is = new InputSource(new StringReader(storyReplacement));
				xr.parse(is);

			} catch (Exception e) {
				System.out.println("XML Pasing Excpetion = " + e);
			}
			
			storyListRecords = StoryXMLHandler.storyList;

			return storyListRecords;

	    }
	    
	    public CommentList doGetComments(int storyID){
	    	
			CommentList commentListRecords = null;
			CommentXMLHandler.commentList = null;
			
			RestClient client = new RestClient(getString(R.string.base_url)+"/get_comm_by_ID.php");
			client.AddParam("ID", ""+storyID);

			try {
				client.Execute(RequestMethod.GET);
			} catch (Exception e) {
				e.printStackTrace();
			}

			String commentResponse = client.getResponse();
			String commentReplacement = null;
			
			try {

				/** Handling XML */
				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser sp = spf.newSAXParser();
				XMLReader xr = sp.getXMLReader();

				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
				CommentXMLHandler myXMLHandler = new CommentXMLHandler();
				xr.setContentHandler(myXMLHandler);
				commentReplacement = commentResponse.replace("\n", "");
				commentReplacement = commentReplacement.trim();

				Log.v("this is response", commentResponse);
				//Log.v("this is replacemment", replacement);
				
				
				InputSource is = new InputSource(new StringReader(commentReplacement));
				xr.parse(is);

			} catch (Exception e) {
				System.out.println("XML Pasing Excpetion = " + e);
			}
			
			commentListRecords = CommentXMLHandler.commentList;
		   // Log.v("COMM SIZE", commentListRecords.getSize()+"" );

			return commentListRecords;

	    }

	}
	
	// Creating Dialog 
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case 1: {
                dialog = new ProgressDialog(this);
                dialog.setMessage("Please wait while loading...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
        }
        return null;
    }
    
    private class CommentListAdapter extends BaseAdapter {

        /**
         * Remember our context so we can use it when constructing views.
         */
        private Context mContext;
        private ArrayList<String> mComments;
        private ArrayList<String> mTimestamp;
        
        public CommentListAdapter(Context context, ArrayList<String> comments, ArrayList<String> timestamp) {
            mContext = context;
            mComments = comments;
            mTimestamp = timestamp;
        }

        public int getCount() {
            return mComments.size();
        }

        /**
         * Since the data comes from an array, just returning the index is
         * sufficent to get at the data. If we were using a more complex data
         * structure, we would return whatever object represents one row in the
         * list.
         * 
         * @see android.widget.ListAdapter#getItem(int)
         */
        public Object getItem(int position) {
            return position;
        }

        /**
         * Use the array index as a unique id.
         */
        public long getItemId(int position) {
            return position;
        }

        /**
         * Make a CommentView to hold each row.
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            CommentView sv;
            if (convertView == null) {
                sv = new CommentView(mContext, mComments.get(position), mTimestamp.get(position));
            } else {
                sv = (CommentView) convertView;
                sv.setTitle(mComments.get(position));
                sv.setDialogue(mTimestamp.get(position));
            }

            return sv;
        }

    }
    
    
    private class CommentView extends LinearLayout {
        public CommentView(Context context, String comment, String dateTime) {
            super(context);

            this.setOrientation(VERTICAL);

            mComment = new TextView(context);
            mComment.setText(comment);
            mComment.setTextSize(20);
            mComment.setTextColor(Color.YELLOW);

            addView(mComment, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

            mDateTime = new TextView(context);
            mDateTime.setText(dateTime);
            addView(mDateTime, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        }

        /**
         * Convenience method to set the title of a SpeechView
         */
        public void setTitle(String comment) {
        	mComment.setText(comment);
        }

        /**
         * Convenience method to set the dialogue of a SpeechView
         */
        public void setDialogue(String dateTime) {
        	mDateTime.setText(dateTime);
        }

        private TextView mComment;
        private TextView mDateTime;
    }
}
